package com.eshop.inventory.thread;

import com.eshop.inventory.constant.ThreadCons;
import com.eshop.inventory.request.Request;
import com.eshop.inventory.request.RequestQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Xukai
 * @description: 请求处理线程池（单例）
 * 单例有很多种方式去实现，这里采取绝对线程安全的一种方式
 * 静态内部类的方式，去初始化单例
 * jvm的机制规定内部类的初始化，不管多少个线程并发去初始化，一定只会发生一次，所以保证了多线程并发安全
 * @createDate: 2018/7/23 01:04
 * @modified By:
 */
public class RequestProcessorThreadPool {

    /**
     * 线程池
     */
    private ExecutorService threadPool = Executors.newFixedThreadPool(ThreadCons.THREAD_NUM);

    private RequestProcessorThreadPool() {
        RequestQueue requestQueue = RequestQueue.getInstance();
        for (int i = 0; i < ThreadCons.THREAD_NUM; i++) {
            ArrayBlockingQueue<Request> queue = new ArrayBlockingQueue<>(ThreadCons.QUEUE_NUM);
            requestQueue.addQueue(queue);
            threadPool.submit(new RequestProcessorThread(queue));
        }
    }

    private static class Singleton {

        private static RequestProcessorThreadPool instance;

        static {
            instance = new RequestProcessorThreadPool();
        }

        public static RequestProcessorThreadPool getInstance() {
            return instance;
        }
    }

    public static RequestProcessorThreadPool getInstance() {
        return Singleton.getInstance();
    }

    /**
     * 初始化的便捷方法
     */
    public static void init() {
        getInstance();
    }
}
